package com.mzj.saas.commons.pdf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * PDF生成工具
 * 
 * @author shun
 * @createDate: 2021年6月16日 下午4:28:20
 * @version: 1.0
 *
 */
public class HtmlToPdfUtils {
	private static final Logger log = LoggerFactory.getLogger(HtmlToPdfUtils.class);
	// windows
	private static String toolWinPath = "E:/setup/wkhtmltopdf/bin/wkhtmltopdf.exe";
	// Linux
	private static String toolLinuxPath = "/usr/local/wkhtmltox/bin/wkhtmltopdf";

	/**
	 * html生成pdf
	 * 
	 * @param srcPath
	 *            文件路径/网页地址
	 * @param destPath
	 *            生成后的文件
	 * @return
	 * @author shun
	 * @date 2021年6月16日
	 */
	public static boolean convert(String srcPath, String destPath) {
		File file = new File(destPath);
		File parent = file.getParentFile();
		if (!parent.exists()) {
			parent.mkdirs();
		}
		StringBuilder cmd = new StringBuilder();
		if (System.getProperty("os.name").indexOf("Windows") == -1) {
			// linux系统下wkhtmltopdf安装路径
			cmd.append(toolLinuxPath);
		} else{
			cmd.append(toolWinPath);
		}
		cmd.append(" ").append(srcPath).append(" ").append(destPath);
		
		
		boolean result = true;
		try {
			Process proc = Runtime.getRuntime().exec(cmd.toString());
			HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(
                    proc.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(
                    proc.getInputStream());
            error.start();
            output.start();
			proc.waitFor();
		} catch (IOException | InterruptedException e) {
			result = false;
			e.printStackTrace();
		}
		return result;
	}

	public static void main(String[] args) {
		HtmlToPdfUtils.convert("C:/Users/admin/Desktop/index3.html", "C:/Users/admin/Desktop/33.pdf");
	}
}